package com.yellowcong.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;
/**
*
*作者:yellowcong
*日期:2017/08/30
*時間:17:08:21
*描述:
*/
public class Demo4 {
	public static void main(String[] args) throws Exception {
		
		BookProxy proxy = new BookProxy(new BookServieImpl());
		
		BookServie book = (BookServie) proxy.getProxy();
		
		String result = book.add("Think in Java");
		
		System.out.println(result);
	}
	
	
}

/**
 * 使用java本生的代理对象需要用到，接口类，实现类
 * @author zhangrw
 * @data 2017/08/31
 */
class BookProxy implements InvocationHandler{
	private Object target ;
	
	public BookProxy(Object target) {
		super();
		this.target = target;
	}
	/**
	 * 将Object绑定到当前的对象上
	 * @param target
	 * @return
	 */
	public Object getProxy() {
		
		//初始化代理对象
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		try {
			System.out.println("proxy before");
			result =  method.invoke(this.target, args);
			System.out.println("proxy end");
		}finally {
			
		}
		return result;
	}
	
}
interface BookServie{
	/**
	 * 添加图书的操作
	 * @return
	 */
	String add(String name);
}

class BookServieImpl implements BookServie{

	@Override
	public String add(String name) {
		System.out.println("Book Add Method");
		return "添加书籍"+name;
	}
}
